package com.kingbi.system.people.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BasicDynaBean;

import com.kingbi.common.MD5;
import com.kingbi.system.people.dao.PeopleDao;
import com.kingbi.system.people.dao.PeopleQuery;
import com.kingbi.system.people.jsfBean.PeopleDataBean;
import com.kingbi.system.people.model.PeopleModel;
import com.kingbi.system.userRole.dao.UserRoleDao;
import com.kingbi.system.userRole.model.UserRoleModel;
import com.kingbi.util.ParasProperty;
import com.kingbi.util.ConstantFiles.UserConstant;

public class PeopleServiceImpl implements PeopleService {

	private PeopleDao peopleDao;
	private UserRoleDao userRoleDao;

	// 分页查询所有用户（单表）
	public List<PeopleModel> listPeople(PeopleModel peopleModel, int start,int max) {
		PeopleQuery peopleQuery = new PeopleQuery();
		peopleQuery.doSearchQuery(peopleModel);
		return peopleDao.findByHQL(peopleQuery.getSearch_query_bud().toString(), peopleQuery.getParams(), start, max);
	}

	// 根据用户ID读取一条记录
	public PeopleModel loadUnit(String userID) {
		return peopleDao.findById(userID);
	}

	// 获取符合条件的总记录数
	public long queryCount(PeopleModel peopleModel) {
		PeopleQuery peopleQuery = new PeopleQuery();
		peopleQuery.doSearchQuery(peopleModel);
		return peopleDao.getCountByHQL(peopleQuery.getSearch_count_bud().toString(), peopleQuery.getParams());
	}

	// 添加用户
	public void savePeople(PeopleModel peopleModel) {
		peopleDao.save(peopleModel);

	}
	//修改之前
	public void saveUser(PeopleModel peopleModel, String[] roles)
    {
		Object checkLevel = ((HttpSession) FacesContext.getCurrentInstance().getExternalContext()
               .getSession(false)).getAttribute(UserConstant.USER_MAP_KEY_CHECK_LEVEL);
		
		peopleModel.setValid("1");
		userRoleDao.delteByHQL("delete UserRoleModel where userId = ?", new String[] { peopleModel
                .getUserId() });
        
        /*for (String role : roles)
        {
        	UserRoleModel userRoleModel =  new UserRoleModel();
            userRoleModel.setUserId(peopleModel.getUserId());
            userRoleModel.setRoleCode(role);
            userRoleDao.save(userRoleModel);
        }*/

		peopleDao.save(peopleModel);

    }

	// 删除用户
	public void deletePeople(String unitID) {
		peopleDao.delete(peopleDao.findById(unitID));
	}

	// 获取角色表的数据
    public List<Object> loadRole() throws SQLException {
		try {
			String queryRoleSql = "SELECT ROLE.ROLE_CODE,ROLE.ROLE_NAME FROM P_ROLE ROLE";
			List<Object> listRole = peopleDao.findBySQL(queryRoleSql, null);
			return listRole;
		} catch (SQLException e) {
			throw e;
		}
	}
    
    // 读用户角色表，根据该用户获得角色
    public List<Object> loadUserRole(String userId) throws SQLException {

		String queryUserRoleSql = "SELECT UR.ROLE_CODE FROM P_USER_ROLE UR WHERE UR.USER_ID = ?";
		List<Object> listUR = new ArrayList<Object>();
		try {
			List<Object> listUserRole = peopleDao.findBySQL(queryUserRoleSql,new Object[] { userId });
			if (listUserRole != null && listUserRole.size() > 0) {
				Iterator<Object> iterUR = listUserRole.iterator();
				while (iterUR.hasNext()) {
					listUR.add(((BasicDynaBean) iterUR.next()).get("role_code"));
				}
				listUserRole = null;
				iterUR = null;
			}
		} catch (SQLException e) {
			throw e;
		}
		return listUR;
	}
    
   // 查询所有用户信息,分页
    public List<Object> getUserAll(String queryCond, int pageRecord,
			int currentPage) throws SQLException {
		List<Object> listUser = null;
		try {
			StringBuffer queryUserSQL = new StringBuffer();
			queryUserSQL.append(" select pu.user_id,pu.user_name,pu.password,pu.phone,pu.mobile,pu.email,pu.remark,");
			queryUserSQL.append(" group_concat(pr.role_code) role_code,group_concat(pr.role_name) role_name");
			queryUserSQL.append(" from p_user pu ");
			queryUserSQL.append(" left join p_user_role pur on pur.user_id=pu.user_id");
			queryUserSQL.append(" left join p_role pr on pr.role_code=pur.role_code");
			queryUserSQL.append(" where pu.valid=1 ");
			queryUserSQL.append(" group by pu.user_id,pu.user_name,pu.password,pu.phone,pu.mobile,pu.email,pu.remark");
			queryUserSQL.append(queryCond);
			queryUserSQL.append(" order by pu.user_id");
			
			listUser = peopleDao.findBySQL(queryUserSQL.toString(), null, pageRecord, currentPage);
		} catch (SQLException e) {
			throw e;
		}
		return listUser;
	}
   
    // 封装用户信息，分页
    public List<PeopleDataBean> getUserItems(String queryCond, int pageRecord,
			int currentPage,long count) throws SQLException {
		List<PeopleDataBean> list = null;
		try {
			List<Object> listUser = getUserAll(queryCond, pageRecord,currentPage);
			if (!listUser.isEmpty()) {       
				list = new ArrayList<PeopleDataBean>();
				PeopleDataBean peopleDataBean = null;
				Iterator<Object> userIter = listUser.iterator();
				BasicDynaBean peopleBean = null;
				while (userIter.hasNext()) {
					peopleBean = (BasicDynaBean) userIter.next();
					peopleDataBean = new PeopleDataBean();
					peopleDataBean.setUserId((String) peopleBean.get("user_id"));
					peopleDataBean.setUserName((String) peopleBean.get("user_name"));
					peopleDataBean.setPassword((String) peopleBean.get("password"));
					//peopleDataBean.setRoleId((String) peopleBean.get("role_id"));
					peopleDataBean.setRoleName((String) peopleBean.get("role_name"));
					peopleDataBean.setPhone((String) peopleBean.get("phone"));
					peopleDataBean.setMobile((String) peopleBean.get("mobile"));
					peopleDataBean.setEmail((String) peopleBean.get("email"));
					peopleDataBean.setRemark((String) peopleBean.get("remark"));
					list.add(peopleDataBean);
				}
			}
		} catch (SQLException e) {
			throw e;
		}
		return list;
	}

    
    // 根据用户的ID 查询角色表和用户角色表，拼凑成JSON串，返回页面
    public String getCheckboxStr(String userId) throws SQLException {
		String sbToStr = "";
		try {
			List<Object> listRole = loadRole();
			BasicDynaBean bean = null;
			if (listRole != null) {
				List<Object> listUR = loadUserRole(userId);
				Iterator<Object> iterRole = listRole.iterator();
				StringBuffer sb = new StringBuffer();
				sb.append("[");
				while (iterRole.hasNext()) {
					bean = (BasicDynaBean) iterRole.next();
					sb.append("[");
					sb.append("'" + bean.get("role_code") + "',");
					sb.append("'" + bean.get("role_name") + "'");
					if (listUR.contains(bean.get("role_code"))) {
						sb.append(",'checked'");
					} else {
						sb.append(",' '");
					}
					sb.append("],");
				}
				sbToStr = sb.toString();
				sbToStr = sbToStr.substring(0, sbToStr.length() - 1) + "]";
				bean = null;
				listRole = null;
			}
		} catch (SQLException e) {
			throw e;
		}
		return sbToStr;
	}
    
    // 添加用户及角色
    public void savePeopleRole(UserRoleModel userRoleModel) {
		userRoleDao.save(userRoleModel);
		//userRoleDao.add_update(userRoleModel);
	}
    
    public int getMaxId (){
    	              
    		StringBuffer queryUserSql = new StringBuffer();
    		queryUserSql.append("SELECT MAX(USER_ROLE_ID) max_role_id FROM P_USER_ROLE");
    		String maxRoleId = "";
			try {
				List<Object> objList = peopleDao.findBySQL(queryUserSql.toString(), null);
				if(!objList.isEmpty()){
	    			BasicDynaBean bean = null;
	    			for(int i=0; i<objList.size(); i++){
	    				bean = (BasicDynaBean) objList.get(i);
	    				maxRoleId = bean.get("max_role_id")!=null ? bean.get("max_role_id").toString():"0";
	    			}
	    		}
			} catch (SQLException e) {
				e.printStackTrace();
			}
    		
    		int maxId = Integer.parseInt(maxRoleId);
    		
			return maxId;       
		
    }    
    //根据用户Id查询新用户model
    
    public PeopleModel LoadUserBySQL(String userId) throws SQLException
    {
		PeopleModel peopleModel = null;
		StringBuffer queryUserSql = new StringBuffer();  
  
		queryUserSql
				.append("SELECT US.USER_ID,US.USER_NAME,US.PASSWORD,US.ROLE_ID,RO.ROLE_NAME,");
		queryUserSql
				.append("US.PHONE,US.MOBILE,US.EMAIL,US.REMARK,US.VALID,US.B_ID,B.B_NAME FROM P_USER US ,P_USER_ROLE UR,P_ROLE RO ");
		queryUserSql
				.append(",P_BANK B WHERE RO.ROLE_CODE = UR.ROLE_CODE AND UR.USER_ID = US.USER_ID AND US.B_ID = B.B_ID AND US.USER_ID = ?");
		List<Object> listUser = peopleDao.findBySQL(queryUserSql.toString(),
				new String[] { userId });     
		System.out.println(listUser + "-----");       
		if (listUser != null && !listUser.isEmpty()) {
			BasicDynaBean userBean = (BasicDynaBean) listUser.get(0);
			peopleModel = new PeopleModel();
			peopleModel.setUserId((String) userBean.get("user_id"));
			peopleModel.setUserName((String) userBean.get("user_name"));
			peopleModel.setPassword((String) userBean.get("password"));
			peopleModel.setPhone((String) userBean.get("phone"));
			peopleModel.setMobile((String) userBean.get("mobile"));
			peopleModel.setEmail((String) userBean.get("email"));
			peopleModel.setRemark((String) userBean.get("remark"));
			peopleModel.setValid((String) userBean.get("valid"));
		}
		return peopleModel;
	}
    
//根据用户Id查询新用户model
    
    public PeopleDataBean findUserInfo(String userId) throws SQLException
    {
    	PeopleDataBean peopleDataBean = null;
		StringBuffer queryUserSql = new StringBuffer();  
  
		queryUserSql
				.append("SELECT US.USER_ID,US.USER_NAME,US.PASSWORD,RO.ROLE_NAME,");
		queryUserSql
				.append("US.PHONE,US.MOBILE,US.EMAIL,US.REMARK,US.VALID FROM P_USER US ,P_USER_ROLE UR,P_ROLE RO ");
		queryUserSql
				.append("WHERE RO.ROLE_CODE = UR.ROLE_CODE AND UR.USER_ID = US.USER_ID AND US.USER_ID = ?");
		List<Object> listUser = peopleDao.findBySQL(queryUserSql.toString(),
				new String[] { userId });     
		System.out.println(listUser + "-----");       
		if (listUser != null && !listUser.isEmpty()) {
			BasicDynaBean userBean = (BasicDynaBean) listUser.get(0);
			peopleDataBean = new PeopleDataBean();
			peopleDataBean.setUserId((String) userBean.get("user_id"));
			peopleDataBean.setUserName((String) userBean.get("user_name"));
			peopleDataBean.setPassword((String) userBean.get("password"));
			//peopleDataBean.setRoleId((String) userBean.get("role_id"));
			peopleDataBean.setPhone((String) userBean.get("phone"));
			peopleDataBean.setMobile((String) userBean.get("mobile"));
			peopleDataBean.setEmail((String) userBean.get("email"));
			peopleDataBean.setRemark((String) userBean.get("remark"));
			peopleDataBean.setValid((String) userBean.get("valid"));
		}
		return peopleDataBean;
	}
    
    // 统计用户
    public long queryUserCount(String queryStr) throws SQLException
    {
        try
        {
        	StringBuffer queryUserSQL = new StringBuffer();
			queryUserSQL.append(" select pu.user_id,pu.user_name,pu.phone,pu.mobile,pu.email,pu.remark,");
			queryUserSQL.append(" group_concat(pr.role_code) role_code,group_concat(pr.role_name) role_name");
			queryUserSQL.append(" from p_user pu ");
			queryUserSQL.append(" left join p_user_role pur on pur.user_id=pu.user_id");
			queryUserSQL.append(" left join p_role pr on pr.role_code=pur.role_code");
			queryUserSQL.append(" where pu.valid=1 ");
			queryUserSQL.append(" group by pu.user_id,pu.user_name,pu.phone,pu.mobile,pu.email,pu.remark");
			queryUserSQL.append(queryStr);
			queryUserSQL.append(" order by pu.user_id");
            List<Object> queryList = peopleDao.findBySQL(queryUserSQL.toString(), null);
            return Long.valueOf(queryList.size()).longValue();
        }
        catch (SQLException e)
        {
            throw e;
        }
    }
    
    //修改密码
    public void setPassword(PeopleModel poepleModel) throws SQLException{
    	StringBuffer sql = new StringBuffer();
    	String psd = "";
    	try {
			psd = ParasProperty.getInstance().initialPassword;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	sql.append("update p_user set password='"+new MD5().getMD5ofStr(psd)+"' where user_id='"+poepleModel.getUserId()+"'");
    	peopleDao.deleteBySQL(sql.toString());//执行update命令
    }
	
	public PeopleDao getPeopleDao() {
		return peopleDao;
	}

	public void setPeopleDao(PeopleDao peopleDao) {
		this.peopleDao = peopleDao;
	}

	public UserRoleDao getUserRoleDao() {
		return userRoleDao;
	}

	public void setUserRoleDao(UserRoleDao userRoleDao) {
		this.userRoleDao = userRoleDao;
	}

	
}
